package com.lottery.im.module.result.ui.good;

import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.Looper;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.TextUtils;
import android.text.style.ForegroundColorSpan;
import android.view.View;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import butterknife.BindView;
import butterknife.OnClick;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.fondesa.recyclerviewdivider.RecyclerViewDivider;
import com.lottery.im.R;
import com.lottery.im.api.Api;
import com.lottery.im.api.result.entity.FictitiousMap;
import com.lottery.im.api.result.entity.FictitiousRecord;
import com.lottery.im.api.result.entity.GsUserInfo;
import com.lottery.im.api.result.entity.SaleGameInfo;
import com.lottery.im.base.BaseSwipeFragment;
import com.lottery.im.constant.Constants;
import com.lottery.im.constant.RxBusCode;
import com.lottery.im.module.result.adapter.FictitiousRecordAdapter;
import com.lottery.im.module.result.presenter.GsPlanDetailPresenter;
import com.lottery.im.module.result.view.GsPlanDetailView;
import com.lottery.im.util.TimerUtils;
import com.lottery.im.util.rxbus.RxBus;
import com.lottery.im.util.transformations.CropCircleTransformation;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;

/**
 * 高手计划详情
 */
public class GsPlanDetailFragment extends BaseSwipeFragment<GsPlanDetailPresenter> implements
    GsPlanDetailView {

  private final static String ID_KEY = "ID_KEY";
  private final static String NAME_KEY = "NAME_KEY";
  private final static String TITLE_KEY = "TITLE_KEY";

  public static GsPlanDetailFragment create(int id, String gameTypeName, String title) {
    GsPlanDetailFragment fragment = new GsPlanDetailFragment();
    Bundle b = new Bundle();
    b.putInt(ID_KEY, id);
    b.putString(NAME_KEY, gameTypeName);
    b.putString(TITLE_KEY, title);
    fragment.setArguments(b);
    return fragment;
  }

  @BindView(R.id.tv_title) TextView mTvTitle;
  @BindView(R.id.list) RecyclerView mList;

  private View mHeaderView;
  private TextView mTvResultDec;
  private TextView mTvCurResult;
  private ImageView mIvPortrait;
  private TextView mTvName;
  private TextView mTvGoodNum;
  private ImageView mIvZan;
  private TextView mTvZan;
  private TextView mTvLastIssue;
  private TextView mTvLastResult;
  private TextView mTvCurIssue;
  private RadioGroup mRgNum;

  private String mGameTypeName;
  private int mId;

  private FictitiousRecordAdapter mAdapter;
  private List<FictitiousRecord> mFictitiousRecords;

  private GsUserInfo mGsUserInfo;
  private SaleGameInfo mSaleGameInfo;
  private Handler mHandler;

  private MyCountDownTimer mCountDownTimer;

  @Override protected int getLayoutResId() {
    return R.layout.fragment_gsplan_detail;
  }

  @Override protected void initPresenter() {
    presenter = new GsPlanDetailPresenter(getActivity(), this, this);
    presenter.init();
  }

  @Override public void initView() {

    if (null == getArguments()) {
      popBackStack();
      return;
    }

    RxBus.get().register(this);

    mGameTypeName = getArguments().getString(NAME_KEY);
    mTvTitle.setText(getArguments().getString(TITLE_KEY) + "近期预测");

    mId = getArguments().getInt(ID_KEY);

    mList.setLayoutManager(new LinearLayoutManager(mActivity));
    RecyclerViewDivider.with(mActivity)
        .size((int) mActivity.getResources().getDimension(R.dimen.line_size))
        .hideLastDivider()
        .build()
        .addTo(mList);

    mFictitiousRecords = new ArrayList<>();
    mAdapter = new FictitiousRecordAdapter(mFictitiousRecords);
    mList.setAdapter(mAdapter);
    mAdapter.addHeaderView(getHeaderView());

    presenter.getById(mId);
    presenter.querySaleGameInfo(mGameTypeName);
    getFictitiousRecord();
  }

  @OnClick(R.id.iv_back) public void onViewClicked() {
    popBackStack();
  }

  private View getHeaderView() {
    if (null == mHeaderView) {
      mHeaderView = getLayoutInflater().inflate(R.layout.layout_fictitiousrecord_header, null);
      mIvPortrait = mHeaderView.findViewById(R.id.iv_portrait);
      mTvName = mHeaderView.findViewById(R.id.tv_name);
      mTvGoodNum = mHeaderView.findViewById(R.id.tv_good_num);
      mIvZan = mHeaderView.findViewById(R.id.iv_zan);
      mTvZan = mHeaderView.findViewById(R.id.tv_zan);
      mTvLastIssue = mHeaderView.findViewById(R.id.tv_last_issue);
      mTvLastResult = mHeaderView.findViewById(R.id.tv_last_result);
      mTvCurIssue = mHeaderView.findViewById(R.id.tv_cur_issue);
      mTvCurResult = mHeaderView.findViewById(R.id.tv_cur_result);
      mTvResultDec = mHeaderView.findViewById(R.id.tv_result_dec);
      mRgNum = mHeaderView.findViewById(R.id.rg_num);
      mRgNum.setOnCheckedChangeListener((group, checkedId) -> getFictitiousRecord());
      RadioButton rb1 = mHeaderView.findViewById(R.id.rb1);
      rb1.setChecked(true);

      mHeaderView.findViewById(R.id.layout_zan).setOnClickListener(v -> {
        if (null != mGsUserInfo) {
          if (mGsUserInfo.getIs_good() == 1) {
            //showToast("已赞");
          } else {
            presenter.good(mId);
          }
        }
      });
    }

    return mHeaderView;
  }

  @Override public void getByIdSuc(GsUserInfo userInfo) {
    mGsUserInfo = userInfo;
    Glide.with(mContext)
        .load(Api.BASEADDRESS + mGsUserInfo.getHead_img())
        .apply(new RequestOptions()
            .bitmapTransform(new CropCircleTransformation())
            .placeholder(R.drawable.icon_conversation_de)
            .error(R.drawable.icon_conversation_de))
        .into(mIvPortrait);
    mTvName.setText(mGsUserInfo.getUser_name());
    mTvGoodNum.setText(mGsUserInfo.getGood_num());
    if (mGsUserInfo.getIs_good() == 0) {
      mIvZan.setVisibility(View.VISIBLE);
      mTvZan.setText("赞");
      mTvZan.setTextColor(ContextCompat.getColor(mActivity, R.color.red_fa));
    } else {
      mIvZan.setVisibility(View.GONE);
      mTvZan.setText("已赞");
      mTvZan.setTextColor(ContextCompat.getColor(mActivity, R.color.text_color_gray_dark));
    }
    mList.setVisibility(View.VISIBLE);
  }

  @Override public void goodSuc() {
    showToast("点赞成功");
    RxBus.get().send(RxBusCode.ZAN_CODE);
    mGsUserInfo.setIs_good(1);
    mIvZan.setVisibility(View.GONE);
    mTvZan.setText("已赞");
    mTvZan.setTextColor(ContextCompat.getColor(mActivity, R.color.text_color_gray_dark));
    presenter.getById(mId);
  }

  @Override public void querySaleGameInfoSuc(SaleGameInfo info) {
    mSaleGameInfo = info;
    String lastIssueID = info.getLastIssueID();
    mTvLastIssue.setText(lastIssueID.substring(lastIssueID.length() - 4, lastIssueID.length()));
    mTvLastResult.setText(info.getResult());
    String issueID = info.getIssueID();
    mTvCurIssue.setText(issueID.substring(lastIssueID.length() - 4, issueID.length()));

    long closeTime = info.getGMTcloseTime();
    long openTime = info.getGMTopenTime();
    long curTime = info.getGMTcurTime();
    if (closeTime - curTime > 0) {
      if (mCountDownTimer != null) {
        mCountDownTimer.cancel();
      }
      mCountDownTimer =
          new MyCountDownTimer(closeTime - openTime, closeTime - curTime,
              Constants.COUNT_DOWN_INTERVAL);
      mCountDownTimer.start();
    } else {
      mTvCurResult.setText(R.string.opening);
      if (mCountDownTimer != null) {
        mCountDownTimer.cancel();
      }
      getFictitiousRecord();
    }
  }

  @Override public void getFictitiousRecordSuc(FictitiousMap map) {

    if (null != mSaleGameInfo && mFictitiousRecords.size() > 0 && mTvCurResult.getText()
        .toString()
        .equals(getResources().getString(R.string.opening))) {
      for (FictitiousRecord record : map.getList()) {
        if (record.getIssueId().equals(mSaleGameInfo.getIssueID())
            && TextUtils.isEmpty(record.getBallResult())) {

          if (null == mHandler) {
            mHandler = new Handler(Looper.getMainLooper());
          }
          mHandler.postDelayed(mRunnable,1500);
          return;
        }
      }
    }

    if (mFictitiousRecords.size() > 0) {
      presenter.querySaleGameInfo(mGameTypeName);
    }

    mFictitiousRecords.clear();
    if (null != map) {
      StringBuffer resultSf = new StringBuffer();
      int index1, index2, index3, index4, index5, index6, index7, index8, index9, index10;
      if (null != map.getList()) {
        mFictitiousRecords.addAll(map.getList());
        if (map.getList().size() > 0) {
          String name = map.getList().get(0).getName();
          resultSf.append(name.substring(name.indexOf("-") + 1, name.length()));
        }
      }
      index1 = resultSf.toString().length();
      resultSf.append(mFictitiousRecords.size());
      index2 = resultSf.toString().length();
      resultSf.append("期统计:命中");
      index3 = resultSf.toString().length();
      resultSf.append(map.getMzNum());
      index4 = resultSf.toString().length();
      resultSf.append("期，命中率");
      index5 = resultSf.toString().length();

      if (mFictitiousRecords.size() == 0) {
        resultSf.append("0.00%");
      } else {
        DecimalFormat df = new DecimalFormat("#0.00");
        resultSf.append(
            df.format(
                Double.valueOf(map.getMzNum() * 100) / Double.valueOf(mFictitiousRecords.size()))
                + "%");
      }
      index6 = resultSf.toString().length();
      resultSf.append("；最大连中");
      index7 = resultSf.toString().length();
      resultSf.append(map.getMaxLZNum());
      index8 = resultSf.toString().length();
      resultSf.append("期，最大连错");
      index9 = resultSf.toString().length();
      resultSf.append(map.getMaxLCNum());
      index10 = resultSf.toString().length();
      resultSf.append("期");
      SpannableStringBuilder style = new SpannableStringBuilder(resultSf.toString());
      style.setSpan(new ForegroundColorSpan(ContextCompat.getColor(mActivity, R.color.red_fa)),
          index1,
          index2,
          Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
      style.setSpan(new ForegroundColorSpan(ContextCompat.getColor(mActivity, R.color.red_fa)),
          index3,
          index4,
          Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
      style.setSpan(new ForegroundColorSpan(ContextCompat.getColor(mActivity, R.color.red_fa)),
          index5,
          index6,
          Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
      style.setSpan(new ForegroundColorSpan(ContextCompat.getColor(mActivity, R.color.red_fa)),
          index7,
          index8,
          Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
      style.setSpan(new ForegroundColorSpan(ContextCompat.getColor(mActivity, R.color.red_fa)),
          index9,
          index10,
          Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

      mTvResultDec.setText(style);
    }
    mAdapter.notifyDataSetChanged();
  }

  private void getFictitiousRecord() {
    int limit = 10;
    switch (mRgNum.getCheckedRadioButtonId()) {
      case R.id.rb1:
        limit = 10;
        break;
      case R.id.rb2:
        limit = 20;
        break;
      case R.id.rb3:
        limit = 30;
        break;
      case R.id.rb4:
        limit = 50;
        break;
      case R.id.rb5:
        limit = 100;
        break;
    }
    presenter.getFictitiousRecord(mId, limit);
  }

  Runnable mRunnable = new Runnable() {
    @Override public void run() {
      getFictitiousRecord();
      mHandler.removeCallbacks(mRunnable);
      mHandler = null;
    }
  };

  class MyCountDownTimer extends CountDownTimer {
    private long max;

    public MyCountDownTimer(long max, long millisInFuture, long countDownInterval) {
      //微调防止跳过
      super(millisInFuture + millisInFuture * 2 / countDownInterval, countDownInterval);
      this.max = max;
    }

    @Override
    public void onTick(long millisUntilFinished) {
      if (mTvCurResult == null) return;
      mTvCurResult.setText(TimerUtils.formatDuring2(millisUntilFinished));
    }

    @Override
    public void onFinish() {
      cancel();
      mTvCurResult.setText(R.string.opening);
      getFictitiousRecord();
    }
  }

  @Override public void onDestroy() {
    super.onDestroy();
    RxBus.get().unRegister(this);
    if (mCountDownTimer != null) {
      mCountDownTimer.cancel();
    }
    mCountDownTimer = null;
    if (null != mHandler){
      mHandler.removeCallbacks(mRunnable);
      mHandler = null;
    }
  }
}
